package cn.sczc.jh.client.service.sys;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.sczc.jh.client.entity.Role;
import cn.sczc.jh.client.entity.RolePermissionRef;
import cn.sczc.jh.client.exception.BusinessException;
import cn.sczc.jh.client.mapper.sys.RoleMapper;

@Service
@Transactional(rollbackFor = Exception.class)
public class RoleService extends ServiceImpl<RoleMapper, Role> {

	@Autowired
	private RoleMapper roleMapper;

	public List<Role> getRoleList() {
		return roleMapper.getRoleList();
	}

	public Page<Role> getRoleByParams(Page<Role> page, Map<String, Object> params) {
		List<Role> list = roleMapper.getRoleByParams(page, params);
		if (list != null && list.size() > 0) {
			for (Role role : list) {
				List<Long> permissionIds = roleMapper.getPermissionIdList(role.getId());
				if (permissionIds != null && permissionIds.size() > 0) {
					role.setPermissionIds(permissionIds);
				}
			}
		}
		page.setRecords(list);
		return page;
	}

	public int addRole(Role role) {
		QueryWrapper<Role> wrapper = new QueryWrapper<>();
		wrapper.eq("name_", role.getName());
		int count = roleMapper.selectCount(wrapper);
		if (count > 0) {
			throw new BusinessException("角色已存在！");
		} else {
			role.setId(IdWorker.getId());
			// role.setCreateBy(WebUtil.getCurrentUser());
			role.setCreateTime(new Date());
			return roleMapper.insert(role);
		}
	}

	public int updateRole(Role role) {
		QueryWrapper<Role> wrapper = new QueryWrapper<>();
		wrapper.ne("id_", role.getId());
		wrapper.eq("name_", role.getName());
		int count = roleMapper.selectCount(wrapper);
		if (count > 0) {
			throw new BusinessException("角色已存在！");
		} else {
			role.setUpdateTime(new Date());
			return roleMapper.updateById(role);
		}
	}

	public int delById(Long id) {
		return roleMapper.deleteById(id);
	}

	public void setPermission(Role role) {
		if (role.getPermissionIds() != null && role.getPermissionIds().size() > 0) {
			roleMapper.delRolePermissionByRoleId(role.getId());
			List<RolePermissionRef> rolePermissionRefs = new ArrayList<RolePermissionRef>();
			for (Long permissionId : role.getPermissionIds()) {
				RolePermissionRef rpr = new RolePermissionRef();
				rpr.setId(IdWorker.getId());
				rpr.setRoleId(role.getId());
				rpr.setPermissionId(permissionId);
				rolePermissionRefs.add(rpr);
			}
			roleMapper.batchAddRolePermission(rolePermissionRefs);
		} else {
			throw new BusinessException("权限不能为空！");
		}

	}

}
